package com.zhuzhe.blog.article.controller;

import com.zhuzhe.blog.aliyun.AliyunUtil;
import com.zhuzhe.blog.base.JsonData;
import com.zhuzhe.blog.base.ResponseData;
import com.zhuzhe.blog.enums.PlatformEnum;
import com.zhuzhe.blog.properties.AliyunProperties;
import com.zhuzhe.blog.properties.BlogProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件控制器
 */
@Api(value = "文件管理接口", description = "文件管理接口，上传或删除图片文件")
@RequestMapping("/file")
@RestController
public class FileController {

    @Autowired
    private BlogProperties blogProperties;

    @ApiOperation("上传文件到OSS服务器")
    @PostMapping("/upload") // /article/file/upload
    @ApiImplicitParam(name = "type", value = "文件渠道:1文章,2用户（头像）,3广告,4问题", required = true)
    public ResponseData<String> upload(@RequestParam("file") MultipartFile file, String type) {
        // 获取阿里云 OSS 相关配置信息
        AliyunProperties aliyun = blogProperties.getAliyun();
        if (Integer.valueOf(type) != 0){
            switch (Integer.valueOf(type)){
                case 1:
                    return AliyunUtil.uploadFileToOss(PlatformEnum.ARTICLE, file, aliyun);
                case 2:
                    return AliyunUtil.uploadFileToOss(PlatformEnum.USER, file, aliyun);
                case 3:
                    return AliyunUtil.uploadFileToOss(PlatformEnum.ADVERT, file, aliyun);
                case 4:
                    return AliyunUtil.uploadFileToOss(PlatformEnum.QUESTION, file, aliyun);

                default:
                    return JsonData.fail("请明确文件渠道");
            }
        }
        return JsonData.success("文件上传成功");
    }

    @ApiImplicitParam(name = "fileUrl", value = "要删除的文件URL", required = true)
    @ApiOperation("根据文件URL删除在OSS服务器中对应文件")
    @DeleteMapping("/delete") // /article/file/delete
    public ResponseData delete(@RequestParam(value = "fileUrl", required = true)
                                     String fileUrl) {
        return AliyunUtil.delete(fileUrl, blogProperties.getAliyun());
    }


}
